package com.mit.web.business.remote
{
	import com.mit.web.view.component.monitor.IMonitorToken;
	import com.mit.web.view.component.monitor.IProgressMonitor;
	
	import flash.display.DisplayObject;
	
	import mx.core.INavigatorContent;

	public class AbstractResponder implements IInvokeResponder
	{
		private var resultListeners:Array;
		private var faultListeners:Array;
		private var defaultFaultListener:Function;
		private var monitorToken:IMonitorToken;
		
		public function AbstractResponder(defaultFaultListerner:Function = null)
		{
			this.defaultFaultListener = defaultFaultListener;
		}
		
		public function addResultListener(handler:Function, ...params):IInvokeResponder
		{
			if(!resultListeners)
				resultListeners = new Array();
			resultListeners.push(new Listener(handler, params));
			return this;
		}
		
		public function addFaultListener(handler:Function, ...params):IInvokeResponder
		{
			if(!faultListeners)
				faultListeners = new Array();
			faultListeners.push(new Listener(handler, params));
			return this;
		}
		
		protected function notifyResultListeners(result:Object, first:int = 0):void{
			try{
				applyHandlers(result, resultListeners);
			}finally{
				if(monitorToken!=null)
					//Make sure hide the progressbar whenever.
					monitorToken.stop();
			}
		}
		
		protected function notifyFaultListeners(fault:Object, first:int = 0):void{
			try{
				applyHandlers(fault, faultListeners);
				if(defaultFaultListener != null)
					defaultFaultListener.apply(null, [fault]);
			}finally{
				if(monitorToken!=null)
					//Make sure hide the progressbar whenever.
					monitorToken.stop();
			}
		}
		
		private function applyHandlers(rtn:Object, handlers:Array):void{
			if(handlers){
				for(var i:int = 0; i < handlers.length; i++){
					var l:Listener = handlers[i];
					var f:Function = l.handler;
					var a:Array = l.arguments;
					a.unshift(rtn);
					f.apply(null, a);
				}
			}
		}
		
		//Show a progress bar
		public function installProgressBar(moniter:IProgressMonitor
										   , parent:DisplayObject
											 , cancelHandler:Function = null):IInvokeResponder{
			if(moniter){
				monitorToken = moniter.begin(this, parent, cancelHandler);
			}
			return this;
		}
		
		protected function clear():void{
			resultListeners = [];
			faultListeners = [];
		}

	}


}